package com.domain.oa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Configuration;

import java.util.Calendar;
import java.util.Map;

@Configuration
public class JWTUtils {
    private static final String SIGNATURE = "!IT_XIAOXIONG@TENPOINT$RJGC171ban#";

    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        // 默认7天过期
        instance.add(Calendar.DATE, 7);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SIGNATURE));  // sign
        return token;
    }

    /**
     * 验证token  合法性
     */
    public static int verifyToken(String token){
        // try最好做一个全局处理，或者在调用方法的地方进行处理，定制化返回提示消息
        try {
            JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        } catch (SignatureVerificationException e) {
            // 签名异常
            return 1;
        }catch (TokenExpiredException e){
            // 令牌过期异常
            return 2;
        }catch (AlgorithmMismatchException e){
            // 算法不一致异常
            return 3;
        }catch (InvalidClaimException e){
            // 失效的payload异常
            return 4;
        }catch (Exception e){
            e.printStackTrace();
            return 5;
        }
        return 0;
    }

    /**
     * 获取token信息
     */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }
}
